<template>
  <div>
    <el-card class="main_card">
      <el-row>
        <el-col :span="8">
          <el-input placeholder="请输入酒店名称" clearable v-model="queryInfo.queryString" @clear="findPage">
            <el-button slot="append" icon="el-icon-search" @click="findPage" />
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button style="margin-left: 10px" @click="insert"  v-hasPermi="['PRE_INSERT']" type="primary">添加信息</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableList"
                stripe v-loading="loading"
                element-loading-text="玩命加载中"
                element-loading-spinner="el-icon-loading">
        <el-table-column type="index" label="序号" />
        <el-table-column prop="hotelName" label="酒店名称" />
        <el-table-column label="缩略图" align="center" width="130">
          <template slot-scope="scope">
            <el-image
                v-if="scope.row.imageUrls"
                style="width: 100px; height: 100px"
                :src="$qiniu + scope.row.imageUrls.split(',')[0]"
                :preview-src-list="previewImages(scope.row.imageUrls.split(','))"/>
            <el-image
                v-if="!scope.row.imageUrls"
                style="width: 100px; height: 100px"
                src=""/>
          </template>
        </el-table-column>
        <el-table-column prop="hotelAddress" label="酒店地址 "/>
        <el-table-column prop="hotelType" label="酒店类型"/>
        <el-table-column prop="hotelPrice" label="酒店价格"/>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column prop="createUser" label="创建用户"/>
        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope" >
            <el-button type="primary"  @click="update(scope.row)" v-hasPermi="['PRE_UPDATE']" icon="el-icon-edit" circle/>
            <el-button type="danger" @click="deleteById(scope.row.id)" v-hasPermi="['PRE_DELETE']" icon="el-icon-delete" circle/>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-if="total>0"
          @size-change="handlePageSize"
          @current-change="handlePageNumber"
          :current-page="queryInfo.pageNumber"
          :page-sizes="[7, 15, 50, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"/>

    </el-card>
    <!--表单添加修改-->
    <el-dialog :title="title" v-loading="loading" :visible.sync="open" width="60%" @colse="dialogClosed">
      <el-form :model="dataForm" :rules="rulesDataForm" ref="dataForm" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="酒店名称" prop="hotelName">
              <el-input
                  v-model="dataForm.hotelName"
                  type="textarea"
                  autosize/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="酒店类别" prop="typeId">
              <el-select placeholder="请选择酒店类别" style="width: 100%" v-model="dataForm.hotelType" clearable>
                <el-option
                    v-for="item in HotelType"
                    :key="item.id"
                    :label="item.title"
                    :value="item.title"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="酒店地址" prop="hotelAddress">
              <el-input v-model="dataForm.hotelAddress"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="景点图片" prop="imageUrl">
          <el-upload
              list-type="picture-card"
              :on-preview="handlePreview"
              ref="imgs"
              :action="uploadUrl"
              :headers="headers"
              :on-remove="handleRemove"
              :before-upload="handleBefore"
              :on-success="handleSuccess"
              :file-list="fileList">
            <i class="el-icon-plus"/>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="酒店价格" prop="hotelPrice">
              <el-input v-model="dataForm.hotelPrice"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人" prop="createUser">
              <el-input v-model="dataForm.createUser"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="clickCancel">取 消</el-button>
                <el-button type="primary" @click="clickOK">确 定</el-button>
            </span>
    </el-dialog>
    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="picDialog">
      <img width="100%" :src="dialogImageUrl"/>
    </el-dialog>

  </div>
</template>
<script>
export  default {
  data(){
    return{
      //分页查询条件
      queryInfo:{
        //页码
        pageNumber:1,
        //页数
        pageSize:7,
        //关键字
        queryString:null
      },
      //表格数据
      tableList:[],
      //总记录数
      total:0,
      //表单的标题
      title:null,
      //是否打开对话框
      open:false,
      //加载
      loading:false,
      //表单数据
      form:{},
      dataForm: {},
      rulesDataForm: {
        title: [
          { required: true, message: "请输入景点分类名称", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
        ],
        hotelType: [
          { required: true, message: "请选择景点类别", trigger: "change" },
        ],
        nutrient: [
          { required: true, message: "请输入浏览人数", trigger: "blur" },
        ],
      },
      uploadUrl: process.env.VUE_APP_BASE_URL +  '/tool/upload',
      headers: {
        Authorization : sessionStorage.getItem('token')
      },
      //图片列表
      picDialog: false,
      dialogImageUrl: '',
      fileList: [],
      //上传文件名
      fileNames: [],
      HotelType:[
        {
          "id": 1,
          "title":'商务型'
        },
        {
          "id": 2,
          "title":'豪华型'
        }
      ]
    }
  },
  /*页面初始化调用方法*/
  created() {
    this.findPage();
  },
  methods:{
    insert(){
      this.fileNames = [];
      this.fileList = [];
      this.title = '新增酒店信息';
      this.dataForm = {};
      this.open = true;
    },
    update(row){
      this.dataForm = {};
      this.fileNames = [];
      this.fileList = [];
      if (row.imageUrls) {
        let urls = row.imageUrls.split(',');
        urls.forEach(item => {
          let url = {url: this.$qiniu + item};
          this.fileList.push(url);
          this.fileNames.push(item);
        });
      }
      this.title = '修改酒店信息';
      this.dataForm = row;
      this.open = true;
    },
    /*分页查询*/
    findPage(){
      this.loading=true;
      this.$ajax.post('/hotel/findPage',this.queryInfo).then((res)=>{
        this.loading=false;
        this.tableList=res.data.data.rows;
        console.log(res.data.data,"1")
        this.total=res.data.data.total;
      });
    },
    /*页码改变事件*/
    handlePageNumber(newPageNumber){
      //将分页的新数据赋值给分页参数
      this.queryInfo.pageNumber=newPageNumber;
      //调分页的方法
      this.findPage();
    },
    /*页数改变的事件*/
    handlePageSize(newPageSize){
      this.queryInfo.pageSize=newPageSize;
      this.findPage();

    },
    deleteById(id){
      this.$confirm('您将删除编号为('+id+')的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //调后端的退出接口
        this.$ajax.delete(`/hotel/delete/${id}`).then((res)=>{
          this.$message.success(res.data.message);
          this.findPage();
          this.queryInfo.pageNumber=1;
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    /*关闭对话框的事件*/
    dialogClose(){
      this.$refs.form.resetFields();
    },
    /*点击取消*/
    clickCancel(){
      this.form={};
      this.open=false;
      this.findPage();
    },
    /*点击确定*/
    clickOK(){
      //表单校验
      this.$refs.dataForm.validate((valid) => {
        if (!valid) return this.$message.error('表单校验不通过，请认真填写后提交！');
        //校验通过验证图片是否上传
        if (this.fileNames.length < 1) return this.$message.error('请上传食物图片，至少一张，至多4张！');
        this.dataForm.imageUrls = this.fileNames.join(',');
        this.loading = true;
        //判断是修改还是添加
        if (this.dataForm.id === null || this.dataForm.id === undefined) {
          //添加
          this.$ajax.post('/hotel/insert', this.dataForm).then((res) => {
            if (!res.data.flag) {
              setTimeout(() => {
                this.loading = false;
              }, 6000);
              return this.$message.error(res.data.message);
            }
            this.open = false;
            this.loading = false;
            this.$message.success(res.data.message);
            this.findPage();
          }).catch(() => {
            setTimeout(() => {
              this.loading = false;
            }, 6000);
          });
        } else {
          //修改
          this.$ajax.post('/hotel/update', this.dataForm).then((res) => {
            if (!res.data.flag) {
              setTimeout(() => {
                this.loading = false;
              }, 6000);
              return this.$message.error(res.data.message);
            }
            this.open = false;
            this.loading = false;
            this.$message.success(res.data.message);
            this.findPage();
          }).catch(() => {
            setTimeout(() => {
              this.loading = false;
            }, 6000);
          });
        }
      });

    },
    dialogClosed() {
      this.fileNames = [];
      //清空表单
      this.$refs.dataForm.resetFields();
    },
    //预览上传的图片
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.picDialog = true;
    },
    /** 上传之前 */
    handleBefore(file) {
      let files = this.$refs.imgs.uploadFiles;
      if (files.length > 3) {
        this.$message.warning('最多上传3张图片哟！');
        return false;
      }
      console.log(file,"asasa")
    },
    /** 上传成功 */
    handleSuccess(res, file, fileList) {
      this.fileNames.push(res.data);
    },
    handleRemove(file, fileList) {
      console.log(fileList);
      console.log('before --> ' + this.fileNames);
      this.fileNames.forEach((item, index) => {
        if (file.response) {
          if (item === file.response.data) {
            this.fileNames.splice(index, 1);
          }
        } else {
          this.fileNames = [];
          // this.fileNames.push();
          fileList.forEach(item => {
            let name = item.url.substring(item.url.lastIndexOf('/') + 1);
            this.fileNames.push(name);
          });
        }

      });
      console.log('after --> ' + this.fileNames);
    },
    previewImages(list) {
      let arr = [];
      list.forEach(item => {
        arr.push(this.$qiniu + item);
      });
      return arr;
    }
  }

}
</script>
<style scoped>

</style>
